<?php

class Application_Model_ExplicitCatanStreetMapper {

    protected $_dbTable;

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_ExplicitCatanStreet');
        }
        return $this->_dbTable;
    }

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Ungueltige Gateway-Klasse fuer Tabellendaten');
        }
        $this->_dbTable = $dbTable;
    }

    public function save(Application_Model_ExplicitCatanStreetModel $street) {
        $data = array(
            'id' => $street->getId(),
            'game_id' => $street->getGame_id(),
            'user_id' => $street->getUser_id(),
        );
        if (null === $street->getId()) {
            unset($data['id']);

            $street->setId($this->getDbTable()->insert($data));
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $data['id']));
        }
        return $this;
    }

    public function find($id, Application_Model_ExplicitCatanStreetModel $street) {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return null;
        }
        $row = $result->current();
        $street->setId($row['id'])
                ->setGame_id($row['game_id'])
                ->setUser_id($row['user_id']);
        return $street;
    }

    public function fetchAll($where = null, $order = null, $count = null, $offset = null) {
        $resultSet = $this->getDbTable()->fetchAll($where, $order, $count, $offset);
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_ExplicitCatanStreetModel();
            $entry->setId($row['id'])
                    ->setGame_id($row['game_id'])
                    ->setUser_id($row['user_id']);
            $entries[] = $entry;
        }
        return $entries;
    }

    public function delete($streetId) {
        if ($streetId instanceof Application_Model_ExplicitCatanStreetModel) {
            $streetId = $streetId->id;
        }
        return $this->getDbTable()->delete(array('id = ?' => $streetId));
    }

}

